package cn.azy.document.tool;

import java.io.*;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;

/**
 * @ Author     ：AZY.
 * @ Date       ：Created in 10:08 2019/10/22
 * @ Description：${DESCRIPTION}
 */
@Slf4j
public class ReadWord {

    public static void word() throws Exception {
//        getWord();
        getTable();
    }

    public static void getWord(){
        String filePath = "F:\\安装包\\2018年降雨量统计表 - 1.doc";
        try{
            FileInputStream in = new FileInputStream(filePath);//载入文档
            WordExtractor ex = new WordExtractor(in);
            String s = ex.getText();
            System.out.println(s.indexOf("昌平区"));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void getTable() throws Exception{
        String filePath = "F:\\安装包\\2018年降雨量统计表 - 1.docx";
        FileInputStream in = new FileInputStream(filePath);//载入文档
        //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
        XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
        List<XWPFParagraph> paragraphs = xwpf.getParagraphs();
        List<String> name = new ArrayList<>();
        List<String> time = new ArrayList<>();
        Map<String , List<Map<String,String>>> excelMap = new HashMap<>();
        for(XWPFParagraph x : paragraphs){
            String s = x.getText();
            if(s.indexOf("昌平区")==0){
                List<Map<String,String>> l = new ArrayList<>();
                excelMap.put(s.substring(s.indexOf("昌平区")+3,s.indexOf("站降水量月报表")).trim(),l);
                name.add(s.substring(s.indexOf("昌平区")+3,s.indexOf("站降水量月报表")).trim());
            }else if(s.trim().length()==0){

            }else{
                s = s.replace("年","-");
                s = s.replace("月","-");
                time.add(s.trim());
            }
        }
        Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
        // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
        int set = 0;
        int num = set;
        // 过滤前面不需要的表格
        for (int i = 0; i < set-1; i++) {
            it.hasNext();
            it.next();
        }

        List<Map<String,String>> list = new ArrayList<>();
        while(it.hasNext()){
            Map<String,String> map = new HashMap<>();
            XWPFTable table = it.next();
//            log.info("这是第" + (num+1) + "个表的数据");
            List<XWPFTableRow> rows = table.getRows();
            //读取每一行数据
            for (int i = 3; i < rows.size()-3; i++) {
                XWPFTableRow  row = rows.get(i);
                String n = name.get(num);
                String st = "";
                String et = "";
                String day = time.get(num);
                String drp = "";
                //读取每一列数据
                List<XWPFTableCell> cells = row.getTableCells();
                boolean b = false;
                for (int j = 1; j < 6; j++) {
                    XWPFTableCell cell = cells.get(j);
                    //输出当前的单元格的数据
                    String s = cell.getText();
                    if(s==null||"".equals(s)){
                        b = true;
                        break;
                    }
//                    System.out.print(s + "\t");
                    if (j == 1) {
                        st = day + s.trim();
                    } else if (j == 2) {
                        if(s.equals("24:00")){
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            Date d = sdf.parse(st);
                            Calendar c = Calendar.getInstance();
                            c.setTime(d);
                            c.add(Calendar.DAY_OF_YEAR,1);
                            st = sdf.format(c.getTime())+" 00:00";
                        }else{
                            st = st +" "+ s.trim();
                        }
                    } else if (j == 3) {
                        if(s.equals("1")){
                            et = day + s.trim();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            Date d = sdf.parse(et);
                            Calendar c = Calendar.getInstance();
                            c.add(Calendar.MONTH,1);
                            et = sdf.format(d);
                        }else{
                            et = day + s.trim();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            Date d = sdf.parse(et);
                            et = sdf.format(d);
                        }
                    } else if (j == 4) {
                        if(s.equals("24:00")){
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            Date d = sdf.parse(et);
                            Calendar c = Calendar.getInstance();
                            c.setTime(d);
                            c.add(Calendar.DAY_OF_YEAR,1);
                            et = sdf.format(c.getTime())+" 00:00";
                        }else{
                            et = et +" "+ s.trim();
                        }
                    } else if (j == 5) {
                        drp = s.trim();
                    }
                }
                if(b){
                    break;
                }
                map.put("name",n);
                map.put("st",st);
                map.put("et",et);
                map.put("drp",drp);
                list.add(map);
                map = new HashMap<>();
//                log.info("name："+n+"  st："+st+"  et："+et+"  drp："+drp);
            }
            num += 1;
        }
//        for(Map.Entry<String,List<Map<String,String>>> entry:excelMap.entrySet()){
//            for(Map<String,String > m : list){
//                if(m.get("name").equals(entry.getKey())){
//                    entry.getValue().add(m);
//                }
//            }
//            exprotExcel(entry.getKey(),entry.getValue());
//        }
        log.info(list.size()+"");
//        exprotExcel("总",list);

    }


    public static void exprotExcel(String key ,List<Map<String,String>> list){
        OutputStream out = null;
        try {
            int columnNumCount = list.size();
            // 读取Excel文档
            File finalXlsxFile = new File("F:\\昌平雨量\\"+key+".xlsx");
            File file = new File("F:\\昌平雨量\\1.xlsx");
            Files.copy(file.toPath(),finalXlsxFile.toPath());
            Workbook workBook = getWorkbok(finalXlsxFile);
            // sheet 对应一个工作页
            Sheet sheet = workBook.getSheetAt(0);
            /**
             * 往Excel中写新数据
             */

            for (int j = 0; j < list.size(); j++) {
                // 创建一行：从第二行开始，跳过属性列
                Row row = sheet.createRow(j + 1);
                // 得到要插入的每一条记录
                Map<String,String> map = list.get(j);
                log.info("这是第" + (j+1) + "行的数据");
                log.info(map.toString());
                // 在一行内循环
                Cell first = row.createCell(0);
                first.setCellValue(map.get("name"));

                Cell second = row.createCell(1);
                second.setCellValue(map.get("st"));

                Cell third = row.createCell(2);
                third.setCellValue(map.get("et"));

                Cell fourth = row.createCell(3);
                fourth.setCellValue(map.get("drp"));
            }
            // 创建文件输出流，准备输出电子表格：这个必须有，否则你在sheet上做的任何操作都不会有效
            out =  new FileOutputStream("F:\\昌平雨量\\"+key+".xlsx");
            workBook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if(out != null){
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断Excel的版本,获取Workbook
     * @param
     * @param
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbok(File file) throws IOException {
        Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if(file.getName().endsWith("xls")){     //Excel&nbsp;2003
            wb = new HSSFWorkbook(in);
        }else if(file.getName().endsWith("xlsx")){    // Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }
}
